#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "const.h"

int Process(char *user_nm);


int main(int argc, char *argv[])
{
    int times, count;
    char user_nm[21];
    time_t start, end;

    if(argc!=2)  times=100;
    else  times=atoi(argv[1]);
    if(times==0)  times=100;

    if(DbsConnect())  exit(1);

    time(&start); 
    for(count=0; count<times; count++)
    {
        sprintf(user_nm, "test%04d", random_int(0,9999));
        if(Process(user_nm))
        {
            printf("bb_nojoin query %d times fail\n", times);
            exit(1);
        }
        printf("user no.%04d %s finished\n", count+1, user_nm);
    }
    time(&end);
    printf("time cost total:%d seconds\n", end-start);

    exit(0);
}


typedef struct
{
    double fee_id;
    struct
    {
        char fee_type[3];
        double fee_at;
    } a_fee_dtl[10];
    int fee_dtl_qt;
} fee_t;
static fee_t a_fee[200];
static int fee_qt;


int Process(char *user_nm)
{
    int result, i, count;
    charge_fee_t ChargeFee;
    charge_fee_dtl_t ChargeFeeDtl;

    count=0;
    strcpy(ChargeFee.status, CHARGE_FEE_STATUS_NOT_PAY);
    strcpy(ChargeFee.user_nm, user_nm);
    if(DbsCHARGE_FEE_CUR_BBNoJoin(DBS_OPEN, &ChargeFee)!=DB_OK)
    {   printf("open cursor fail\n");  return -1;   }
    while(1)
    {
        result=DbsCHARGE_FEE_CUR_BBNoJoin(DBS_FETCH, &ChargeFee);
        if(result!=DB_OK && result!=DB_NOTFOUND)
        {   printf("fetch cursor fail\n");  return -1;   }
        if(result==DB_NOTFOUND)  break;

        a_fee[count].fee_id=ChargeFee.fee_id;
        count++;
/*
        if(count>=20)  break;
*/
    }
    if(DbsCHARGE_FEE_CUR_BBNoJoin(DBS_CLOSE, &ChargeFee)!=DB_OK)
    {   printf("close cursor fail\n");  return -1;   }
    fee_qt=count;

    for(i=0; i<fee_qt; i++)
    {
        count=0;
        ChargeFeeDtl.fee_id=a_fee[i].fee_id;
        if(DbsCHARGE_FEE_DTL_CUR_BBNoJoin(DBS_OPEN, &ChargeFeeDtl)!=
               DB_OK)
        {   printf("open cursor fail\n");  return -1;   }
        while(1)
        {
            result=DbsCHARGE_FEE_DTL_CUR_BBNoJoin(DBS_FETCH,
                       &ChargeFeeDtl);
            if(result!=DB_OK && result!=DB_NOTFOUND)
            {   printf("fetch cursor fail\n");  return -1;   }
            if(result==DB_NOTFOUND)  break;

            strcpy(a_fee[i].a_fee_dtl[count].fee_type,
                ChargeFeeDtl.fee_type);
            a_fee[i].a_fee_dtl[count].fee_at=ChargeFeeDtl.fee_at;
            count++; 
        }
        if(DbsCHARGE_FEE_DTL_CUR_BBNoJoin(DBS_CLOSE, &ChargeFeeDtl)!=
               DB_OK)
        {   printf("open cursor fail\n");  return -1;   }
        a_fee[i].fee_dtl_qt=count;
    }

    return 0;
}
